﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.DeviceManage.Project;
using ProduceBasicData.Domain.DeviceManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.DeviceManage.Project
{
    /// <summary>
    /// 更新项目表单信息
    /// </summary>
    public class UpdateProjectFormHandler : IRequestHandler<UpdateProjectFormCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<ProjectForm> _projectFormRepository;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="projectFormRepository"></param>
        /// <param name="mapper"></param>
        public UpdateProjectFormHandler(IBaseRespository<ProjectForm> projectFormRepository, IMapper mapper)
        {
            _projectFormRepository = projectFormRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 修改项目表单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(UpdateProjectFormCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var projectForm = await _projectFormRepository.GetModelAsync(request.Id);
                if (projectForm == null)
                {
                    // 项目表单不存在时返回错误信息
                    return new ApiResult<int>
                    {
                        Msg = "项目表单不存在",
                        Code = ApiEnum.Failed
                    };
                }
                // 将请求数据映射到现有项目表单对象（更新操作）
                _mapper.Map(request, projectForm);

                // 更新数据库
                await _projectFormRepository.Update(projectForm);

                // 返回成功结果
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "修改成功",
                    Data = projectForm.Id
                };
            }
            catch (Exception ex)
            {
                // 异常时返回错误信息
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"修改失败，{ex.Message}",
                };
            }
        }
    }
}
